package com.smart.community.property.controller;

import java.util.List;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.smart.community.commons.enums.RoleCodeEnum;
import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.result.Result;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.property.dto.AddEmployeeDTO;
import com.smart.community.property.dto.EmployeeQueryDTO;
import com.smart.community.property.dto.UpdateEmployeeDTO;
import com.smart.community.property.service.IPropertyEmployeeService;
import com.smart.community.property.vo.EmployeeVO;
import com.smart.community.property.vo.UserVO;

import cn.dev33.satoken.annotation.SaCheckPermission;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

/**
 * 物业公司员工管理控制器
 * 
 * @author Wu.Liang
 * @since 2025-01-21
 */
@RestController
@RequestMapping("/property/employees")
@Tag(name = "物业公司员工管理", description = "物业公司员工管理相关接口")
@Slf4j
@Validated
public class PropertyEmployeeController {

    @Autowired
    private IPropertyEmployeeService propertyEmployeeService;

    /**
     * 获取物业公司员工列表
     */
    @GetMapping("/{propertyCompanyId}")
    @Operation(summary = "获取物业公司员工列表", description = "分页查询物业公司的员工列表")
    @SaCheckPermission("property:employee:view")
    public Result<PageResult<EmployeeVO>> getPropertyCompanyEmployees(
            @Parameter(description = "物业公司ID") @PathVariable @NotNull Long propertyCompanyId,
            EmployeeQueryDTO queryDTO) throws Exception {
        log.info("获取物业公司员工列表，物业公司ID：{}，查询参数：{}", propertyCompanyId, queryDTO);
        
        // 权限检查：非超级管理员只能查看自己物业公司的员工
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (!SecurityUtils.hasRole(RoleCodeEnum.SUPER_ADMIN.getCode())) {
            // 检查当前用户是否属于该物业公司
            if (!propertyEmployeeService.isUserBelongToPropertyCompany(currentUserId, propertyCompanyId)) {
                return Result.fail("无权限查看该物业公司的员工信息");
            }
        }
        
        PageResult<EmployeeVO> result = propertyEmployeeService.getPropertyCompanyEmployees(propertyCompanyId, queryDTO);
        return Result.success("查询成功", result);
    }

    /**
     * 添加员工到物业公司
     */
    @PostMapping("/{propertyCompanyId}")
    @Operation(summary = "添加员工到物业公司", description = "将用户添加为物业公司员工")
    @SaCheckPermission("property:employee:create")
    public Result<Void> addEmployeeToPropertyCompany(
            @Parameter(description = "物业公司ID") @PathVariable @NotNull Long propertyCompanyId,
            @RequestBody @Valid AddEmployeeDTO addEmployeeDTO) throws Exception {
        log.info("添加员工到物业公司，物业公司ID：{}，员工信息：{}", propertyCompanyId, addEmployeeDTO);
        
        // 权限检查：非超级管理员只能为自己的物业公司添加员工
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (!SecurityUtils.hasRole(RoleCodeEnum.SUPER_ADMIN.getCode())) {
            if (!propertyEmployeeService.isUserBelongToPropertyCompany(currentUserId, propertyCompanyId)) {
                return Result.fail("无权限为该物业公司添加员工");
            }
        }
        
        boolean success = propertyEmployeeService.addEmployeeToPropertyCompany(propertyCompanyId, addEmployeeDTO);
        if (success) {
            return Result.success(null);
        } else {
            return Result.fail("添加员工失败");
        }
    }

    /**
     * 更新员工信息
     */
    @PutMapping("/{propertyCompanyId}/{employeeId}")
    @Operation(summary = "更新员工信息", description = "更新物业公司员工的基本信息")
    @SaCheckPermission("property:employee:edit")
    public Result<Void> updateEmployeeInfo(
            @Parameter(description = "物业公司ID") @PathVariable @NotNull Long propertyCompanyId,
            @Parameter(description = "员工关联ID") @PathVariable @NotNull Long employeeId,
            @RequestBody @Valid UpdateEmployeeDTO updateEmployeeDTO) throws Exception {
        log.info("更新员工信息，物业公司ID：{}，员工ID：{}，更新信息：{}", propertyCompanyId, employeeId, updateEmployeeDTO);
        
        // 权限检查：非超级管理员只能编辑自己物业公司的员工
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (!SecurityUtils.hasRole(RoleCodeEnum.SUPER_ADMIN.getCode())) {
            if (!propertyEmployeeService.isUserBelongToPropertyCompany(currentUserId, propertyCompanyId)) {
                return Result.fail("无权限编辑该物业公司的员工信息");
            }
        }
        
        boolean success = propertyEmployeeService.updateEmployeeInfo(propertyCompanyId, employeeId, updateEmployeeDTO);
        if (success) {
            return Result.success(null);
        } else {
            return Result.fail("更新员工信息失败");
        }
    }

    /**
     * 移除员工
     */
    @DeleteMapping("/{propertyCompanyId}/{employeeId}")
    @Operation(summary = "移除员工", description = "将员工从物业公司中移除")
    @SaCheckPermission("property:employee:delete")
    public Result<Void> removeEmployeeFromPropertyCompany(
            @Parameter(description = "物业公司ID") @PathVariable @NotNull Long propertyCompanyId,
            @Parameter(description = "员工关联ID") @PathVariable @NotNull Long employeeId) throws Exception {
        log.info("移除员工，物业公司ID：{}，员工ID：{}", propertyCompanyId, employeeId);
        
        // 权限检查：非超级管理员只能移除自己物业公司的员工
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (!SecurityUtils.hasRole(RoleCodeEnum.SUPER_ADMIN.getCode())) {
            if (!propertyEmployeeService.isUserBelongToPropertyCompany(currentUserId, propertyCompanyId)) {
                return Result.fail("无权限移除该物业公司的员工");
            }
        }
        
        boolean success = propertyEmployeeService.removeEmployeeFromPropertyCompany(propertyCompanyId, employeeId);
        if (success) {
            return Result.success(null);
        } else {
            return Result.fail("移除员工失败");
        }
    }

    /**
     * 搜索可分配的用户
     */
    @GetMapping("/users/search")
    @Operation(summary = "搜索可分配的用户", description = "搜索可以添加到物业公司的用户")
    @SaCheckPermission("property:employee:create")
    public Result<List<UserVO>> searchAvailableUsers(
            @Parameter(description = "搜索关键词") @RequestParam String keyword,
            @Parameter(description = "排除的物业公司ID") @RequestParam(required = false) Long excludePropertyCompanyId) throws Exception {
        log.info("搜索可分配的用户，关键词：{}，排除物业公司ID：{}", keyword, excludePropertyCompanyId);
        
        List<UserVO> users = propertyEmployeeService.searchAvailableUsers(keyword, excludePropertyCompanyId);
        return Result.success("搜索成功", users);
    }

    /**
     * 批量添加员工
     */
    @PostMapping("/{propertyCompanyId}/batch")
    @Operation(summary = "批量添加员工", description = "批量将用户添加为物业公司员工")
    @SaCheckPermission("property:employee:create")
    public Result<Void> batchAddEmployees(
            @Parameter(description = "物业公司ID") @PathVariable @NotNull Long propertyCompanyId,
            @RequestBody @Valid List<AddEmployeeDTO> addEmployeeDTOList) throws Exception {
        log.info("批量添加员工，物业公司ID：{}，员工数量：{}", propertyCompanyId, addEmployeeDTOList.size());
        
        // 权限检查：非超级管理员只能为自己的物业公司添加员工
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (!SecurityUtils.hasRole(RoleCodeEnum.SUPER_ADMIN.getCode())) {
            if (!propertyEmployeeService.isUserBelongToPropertyCompany(currentUserId, propertyCompanyId)) {
                return Result.fail("无权限为该物业公司添加员工");
            }
        }
        
        boolean success = propertyEmployeeService.batchAddEmployees(propertyCompanyId, addEmployeeDTOList);
        if (success) {
            return Result.success(null);
        } else {
            return Result.fail("批量添加员工失败");
        }
    }

    /**
     * 获取员工详情
     */
    @GetMapping("/{propertyCompanyId}/{employeeId}")
    @Operation(summary = "获取员工详情", description = "获取物业公司员工的详细信息")
    @SaCheckPermission("property:employee:view")
    public Result<EmployeeVO> getEmployeeDetail(
            @Parameter(description = "物业公司ID") @PathVariable @NotNull Long propertyCompanyId,
            @Parameter(description = "员工关联ID") @PathVariable @NotNull Long employeeId) throws Exception {
        log.info("获取员工详情，物业公司ID：{}，员工ID：{}", propertyCompanyId, employeeId);
        
        // 权限检查：非超级管理员只能查看自己物业公司的员工
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (!SecurityUtils.hasRole(RoleCodeEnum.SUPER_ADMIN.getCode())) {
            if (!propertyEmployeeService.isUserBelongToPropertyCompany(currentUserId, propertyCompanyId)) {
                return Result.fail("无权限查看该物业公司的员工信息");
            }
        }
        
        EmployeeVO employee = propertyEmployeeService.getEmployeeDetail(propertyCompanyId, employeeId);
        return Result.success("查询成功", employee);
    }
} 